package org.example.watermark;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.example.data.WaterSensor;
import org.example.function.WaterSensorMapFunction;
import org.example.partition.MyPartitioner;

import java.time.Duration;

/**
 * 空闲等待的处理
 */
public class WatermarkIdlenessDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);

        SingleOutputStreamOperator<Integer> socketDS = env.socketTextStream("localhost", 9999)
                .partitionCustom(new MyPartitioner(), value -> value)
                .map(r -> Integer.parseInt(r))
                .assignTimestampsAndWatermarks(WatermarkStrategy.<Integer>forMonotonousTimestamps()
                        .withTimestampAssigner((r, l) -> r * 1000)
                        .withIdleness(Duration.ofSeconds(5))
                );


        socketDS.keyBy(r -> r % 2)
                .window(TumblingEventTimeWindows.of(Time.seconds(10)))
                .process(new ProcessWindowFunction<Integer, String, Integer, TimeWindow>() {
                    @Override
                    public void process(Integer s, ProcessWindowFunction<Integer, String, Integer, TimeWindow>.Context context, Iterable<Integer> elements, Collector<String> out) throws Exception {
                        long start = context.window().getStart();
                        String startDate = DateFormatUtils.format(start, "yyyy-MM-dd HH:mm:ss.SSS");
                        long end = context.window().getEnd();
                        String endDate = DateFormatUtils.format(end, "yyyy-MM-dd HH:mm:ss.SSS");
                        long l = elements.spliterator().estimateSize();
                        out.collect("key为：" + s + "的窗口[" + startDate + "," + endDate + ")中一共有" + l + "条数据,elements:" + elements.toString());
                    }
                }).print();

        env.execute("WatermarkMonoDemo");

    }
}
